package api

import (
	"context"
	"net/http"
	"sdc/repository/db/dao"
	"sdc/repository/db/model"
	"sdc/service"
	"strconv"

	"github.com/gin-gonic/gin"
)

// CreateProject 创建筹款项目

func CreateProject(c *gin.Context) {
	userID := c.GetUint64("user_id")

	//这标注间只能有一个空格不然会报错
	var req struct {
		Title        string  `json:"title" binding:"required"`
		CategoryID   uint    `json:"category_id" binding:"required"`
		TargetAmount float64 `json:"target_amount" binding:"required,gt=0"`
		Description  string  `json:"description" binding:"required"`
		Image        string  `json:"images" binding:"required,min=1"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
			"data": err.Error(),
		})
		return
	}

	project := &model.Project{
		UserID:       userID,
		Title:        req.Title,
		CategoryID:   req.CategoryID,
		TargetAmount: req.TargetAmount,
		Description:  req.Description,
		Images:       req.Image,
		Status:       0, // 待审核
	}

	// 获取数据库连接，全局数据库连接
	db := dao.NewDBClient(context.Background())
	service := service.NewProjectService(db)
	if err := service.CreateProject(project); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "创建失败",
			"data": err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "创建成功",
		"data": project,
	})
}

// GetProject 获取项目详情
func GetProject(c *gin.Context) {
	projectID, _ := strconv.ParseUint(c.Param("id"), 10, 64)

	// 获取数据库连接，全局数据库连接
	db := dao.NewDBClient(context.Background())
	service := service.NewProjectService(db)
	project, err := service.GetProjectDetail(projectID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "获取项目详情失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "success",
		"data": project,
	})
}

// UpdateProject 更新项目
func UpdateProject(c *gin.Context) {
	userID := c.GetUint64("user_id")
	projectID, _ := strconv.ParseUint(c.Param("id"), 10, 64)

	var req struct {
		Title       string   `json:"title" binding:"required"`
		Description string   `json:"description" binding:"required"`
		Images      []string `json:"images" binding:"required,min=1"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}

	// 获取数据库连接，全局数据库连接
	db := dao.NewDBClient(context.Background())
	service := service.NewProjectService(db)
	// 检查项目所有权
	if !service.CheckProjectOwner(projectID, userID) {
		c.JSON(http.StatusForbidden, gin.H{
			"code": 403,
			"msg":  "无权限操作",
		})
		return
	}

	// 更新项目
	if err := service.UpdateProject(projectID, req.Title, req.Description, req.Images); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "更新失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "更新成功",
	})
}

// DeleteProject 删除项目
func DeleteProject(c *gin.Context) {
	userID := c.GetUint64("user_id")
	projectID, _ := strconv.ParseUint(c.Param("id"), 10, 64)

	// 获取数据库连接，全局数据库连接
	db := dao.NewDBClient(context.Background())
	service := service.NewProjectService(db)
	// 检查项目所有权
	if !service.CheckProjectOwner(projectID, userID) {
		c.JSON(http.StatusForbidden, gin.H{
			"code": 403,
			"msg":  "无权限操作",
		})
		return
	}

	// 删除项目
	if err := service.DeleteProject(projectID); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
}

// ListProjects 项目列表
func ListProjects(c *gin.Context) {
	var req struct {
		CategoryID uint   `form:"category_id"`
		Status     int8   `form:"status"`
		Keyword    string `form:"keyword"`
		Page       int    `form:"page,default=1"`
		PageSize   int    `form:"page_size,default=10"`
	}

	if err := c.ShouldBindQuery(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}

	// 获取数据库连接，全局数据库连接
	db := dao.NewDBClient(context.Background())
	service := service.NewProjectService(db)
	projects, total, err := service.ListProjects(req.CategoryID, req.Status, req.Keyword, req.Page, req.PageSize)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "success",
		"data": gin.H{
			"list":  projects,
			"total": total,
			"page":  req.Page,
			"size":  req.PageSize,
		},
	})
}

// AddProjectUpdate 添加项目动态
func AddProjectUpdate(c *gin.Context) {
	userID := c.GetUint64("user_id")
	projectID, _ := strconv.ParseUint(c.Param("id"), 10, 64)

	var req struct {
		Content string `json:"content" binding:"required"`
		Images  string `json:"images"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}

	// 获取数据库连接，全局数据库连接
	db := dao.NewDBClient(context.Background())
	service := service.NewProjectService(db)
	// 检查项目所有权
	if !service.CheckProjectOwner(projectID, userID) {
		c.JSON(http.StatusForbidden, gin.H{
			"code": 403,
			"msg":  "无权限操作",
		})
		return
	}

	update := &model.ProjectUpdate{
		ProjectID: projectID,
		Content:   req.Content,
		Images:    req.Images,
	}

	if err := service.AddProjectUpdate(update); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "添加动态失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
}

// 获取项目动态
func ListProjectUpdates(c *gin.Context) {
	projectID, _ := strconv.ParseUint(c.Param("id"), 10, 64)

	// 获取数据库连接，全局数据库连接
	db := dao.NewDBClient(context.Background())
	service := service.NewProjectService(db)
	updates, err := service.ListProjectUpdates(projectID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "获取项目动态失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "success",
		"data": updates,
	})
}

// UploadDocument 上传项目材料
func UploadDocument(c *gin.Context) {
	userID := c.GetUint64("user_id")
	projectID, _ := strconv.ParseUint(c.Param("id"), 10, 64)

	var req struct {
		Type    int8   `json:"type" binding:"required,oneof=1 2 3"`
		FileURL string `json:"file_url" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}

	// 获取数据库连接，全局数据库连接
	db := dao.NewDBClient(context.Background())
	service := service.NewProjectService(db)
	// 检查项目所有权
	if !service.CheckProjectOwner(projectID, userID) {
		c.JSON(http.StatusForbidden, gin.H{
			"code": 403,
			"msg":  "无权限操作",
		})
		return
	}

	doc := &model.ProjectDocument{
		ProjectID: projectID,
		Type:      req.Type,
		FileURL:   req.FileURL,
		Status:    1,
	}

	if err := service.AddProjectDocument(doc); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "上传失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "上传成功",
	})
}

// ListAuditProjects 待审核项目列表
func ListAuditProjects(c *gin.Context) {
	db := dao.NewDBClient(context.Background())
	service := service.NewProjectService(db)

	projects, err := service.ListAuditProjects()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "获取待审核项目失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "success",
		"data": projects,
	})
}

// AuditProject 审核项目
func AuditProject(c *gin.Context) {
	projectID, _ := strconv.ParseUint(c.Param("id"), 10, 64)

	db := dao.NewDBClient(context.Background())
	service := service.NewProjectService(db)

	service.AuditProject(projectID, 2)

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "审核成功",
	})
}
